package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Override
    @Async
    public void autoScanWmNews(Long newsId) throws Exception {
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }
        // 1. 查询新闻信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }
        // 2. 提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        // 3. 提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imagesList = getImages(images, content);

        String textFromOcr = ocrCheck(imagesList);
        text = text +"_" + textFromOcr;

        // 加入DFA自动检测
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            updateWmNews(2, "dfa审核没通过", null, newsId.intValue());
            return;
        }


        // 5. 审核文字
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(textScan, newsId.intValue());
        if (!textScanResult) {
            log.warn("文字审核失败");
            return;
        }

        // 4. 审核图片
        Map imageScan = greenImageScan.imageScan(imagesList);
        Boolean imageScanResult = checkResult(imageScan, newsId.intValue());
        if (!imageScanResult) {
            log.warn("图片审核失败");
            return;
        }

        // 6. 调用文章保存
        ArticleDto dto = wmNews2Dto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("文章保存失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();

        // 将articleId更新到WmNews表
        updateWmNews(9, "审核通过", articleId, newsId.intValue());
    }

    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);
            builder.append("_").append(text);
        }
        return builder.toString();
    }

    /**
     * @param text
     * @return
     */
    private Boolean dfaCheck(String text) {
        if (StringUtils.isBlank(text)) {
            return true;
        }
        // 1. 调用mapper提取出所有的敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return true;
        }
        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }
        // 2. DFA初始化
        SensitiveWordUtil.initMap(words);
        // 3. 使用DFAutils
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);

        return CollectionUtils.isEmpty(result);
    }

    /**
     * @param wmNews
     * @return
     */
    public ArticleDto wmNews2Dto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }

        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        dto.setLayout(wmNews.getType());

        Integer channelId = wmNews.getChannelId();
        if (channelId != null) {
            WmChannel wmChannel = wmChannelService.getById(channelId);
            dto.setChannelName(wmChannel.getName());
        }

        Integer userId = wmNews.getUserId();
        if (userId != null) {
            WmUser user = wmUserService.getById(userId);
            dto.setAuthorName(user.getName());
        }
        return dto;
    }

    /**
     * @param status
     * @param reason
     * @param articleId
     * @param newsId
     * @return
     */
    private Boolean updateWmNews(Integer status, String reason, Long articleId, Integer newsId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setReason(reason);
        wmNews.setStatus(status.shortValue());
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }
        return wmNewsService.updateById(wmNews);
    }

    /**
     * @param result
     * @param newsId
     * @return
     */
    private Boolean checkResult(Map result, Integer newsId) {
        if (CollectionUtils.isEmpty(result)) {
            return true;
        }

        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)) {
            return true;
        } else if ("block".equals(suggestion)) {
            updateWmNews(2, "未通过", null, newsId);
            return false;
        } else if ("review".equals(suggestion)) {
            updateWmNews(3, "转人工审核", null, newsId);
            return false;
        }
        return true;
    }


    /**
     * @param images
     * @param content
     * @return
     */
    private List<byte[]> getImages(String images, String content) {
        List<String> finalList = new ArrayList<>();

        //提取封面图
        if (StringUtils.isNotEmpty(images)) {
            String[] split = images.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                List<String> list = Arrays.asList(split);
                finalList.addAll(list);
            }
        }

        //提取内容图
        if (StringUtils.isNotEmpty(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map item : maps) {
                    if (CollectionUtils.isEmpty(item)) {
                        continue;
                    }

                    Object type = item.get("type");
                    if ("image".equals(type)) {
                        String value = (String) item.get("value");
                        finalList.add(value);
                    }
                }
            }
        }

        //声明一个List<byte[]>
        List<byte[]> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(finalList)) {
            for (String url : finalList) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                byte[] bytes = minIoTemplate.downLoadFile(url);
                result.add(bytes);
            }
        }
        return result;
    }


    /**
     * 提取新闻文字
     *
     * @param title
     * @param content
     * @return
     */
    private String getText(String title, String content) {
        if (StringUtils.isEmpty(content)) {
            return title;
        }
        // 1. 提取content中的文字内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return title;
        }
        StringBuilder builder = new StringBuilder();
        for (Map item : maps) {
            if (CollectionUtils.isEmpty(item)) {
                continue;
            }
            Object type = item.get("type");
            if ("text".equals(type)) {
                String value = (String) item.get("value");
                builder.append(value);
            }
        }
        // 2. 将title和content组合
        builder.append("_").append(title);
        return builder.toString();
    }

    @Autowired
    private IScheduleClient scheduleClient;

    @Scheduled(fixedRate = 1000)
    public void getTask() {
        ResponseResult responseResult = scheduleClient.pullTask();
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("消费失败");
            return;
        }
        Object data = responseResult.getData();
        if (data == null) {
            log.warn("没有可消费的任务");
            return;
        }

        String string = JSON.toJSONString(data);
        if (StringUtils.isEmpty(string)) {
            log.warn("没有可消费的任务2");
            return;
        }

        Task task = JSON.parseObject(string, Task.class);
        if (task == null) {
            log.warn("没有可消费的任务");
            return;
        }
        byte[] parameters = task.getParameters();

        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (wmNews == null) {
            log.warn("参数缺失");
            return;
        }

        try {
            autoScanWmNews(wmNews.getId().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
